//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package zmee.sso;

import com.alibaba.excel.util.ObjectUtils;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.login.thirdauth.ThirdSSOAuthHandler;
import kd.bos.login.thirdauth.UserAuthResult;
import kd.bos.login.thirdauth.UserProperType;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.url.UrlService;
import kd.bos.util.RevProxyUtil;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.jasig.cas.client.authentication.AuthenticationRedirectStrategy;
import org.jasig.cas.client.authentication.DefaultAuthenticationRedirectStrategy;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Enumeration;
import java.util.Map;
import java.util.stream.Collectors;

public class YSPLSSOServerPlugin implements ThirdSSOAuthHandler {
    private static Log logger = LogFactory.getLog(YSPLSSOServerPlugin.class);
    private String serverName;
    private String service;
    private AuthenticationRedirectStrategy authenticationRedirectStrategy = new DefaultAuthenticationRedirectStrategy();
    private static String CLIENT_ID = "fhmOyzstUZ";
    private static String CLIENT_SECRET = "760bd08e-9559-4342-8d6a-6755a13d027a";
    private static String AUTHORIZE_URL = "https://ids.wzgroup.cn/profile/oauth2/authorize";
    private static String ACCESSTOKEN_URL = "https://ids.wzgroup.cn/profile/oauth2/accessToken";
    private static String USER_URL = "https://ids.wzgroup.cn/profile/oauth2/profile";
    private static String CALLBACK_URL = "https://opc.zmeeol.com/";
    private static String SSOLOGIN_URL = "https://ids.wzgroup.cn/login.html";
    private static String CQLOGIN_URL = "https://ids.wzgroup.cn/login.html";
    private static String LOGOUT_URL;
    private static String ACCOUNT_ID = "1550813461213085696";
    // private static String ACCOUNT_ID="1386959356490153984";
    //private static String YYACCOUNT_ID="1386959356490153984";
    private static String YYACCOUNT_ID = "1550813461213085696";
    private static ThreadLocal<Boolean> threadLocal;

    /**
     * 请求地址
     */
    private static String REQUESTURL1 = "http://gys.zmeeol.com/";
    private static String REQUESTURL2 = "http://gys.zmeeol.com";

    static {
        LOGOUT_URL = "https://ids.wzgroup.cn/logout?service=" + CALLBACK_URL + "/index.html";
        threadLocal = new ThreadLocal();
    }

    public YSPLSSOServerPlugin() {
    }


    public void callTrdSSOLogin(HttpServletRequest request, HttpServletResponse response, String backUrl) {
        //用户需要登录的地址
//        String loginUrl = "http://opctest.zmeeol.com/ierp/login.html";
//        try {
//            response.sendRedirect(loginUrl);
//        }
//        catch (IOException e) {
//            e.printStackTrace();
//        }


        try {
            String redirectUrl = CQLOGIN_URL;
            logger.info("（PLSSOServerPlugin）callTrdSSOLogin()-redirectUrl" + redirectUrl);
            String appType = request.getParameter("apptype");
            logger.info("（PLSSOServerPlugin）callTrdSSOLogin()-appType" + appType);
            logger.info("（PLSSOServerPlugin）callTrdSSOLogin()-request" + request.getParameterNames());
            String tenantId = RevProxyUtil.getTenantCode(request);
            String server = UrlService.getDomainContextUrl(tenantId);
            logger.info("（PLSSOServerPlugin）callTrdSSOLogin()- Request地址1：" + request.getRequestURL().toString());
            logger.info("（PLSSOServerPlugin）callTrdSSOLogin()- RequestQueryString1：" + request.getQueryString());


            String requestURL = request.getRequestURL().toString();

            //根据刘艳峰老师需求：httpServletRequest.getRequestURL().equals("http://gys.zmeeol.com") ，条件成立时 设置重定向url为 http://gys.zmeeol.com/login.html
            String loginUrl = "http://gys.zmeeol.com/login.html";
            logger.info("单点登录域名=============" + request.getRequestURI());
            if (REQUESTURL1.equals(requestURL) || REQUESTURL2.equals(requestURL)) {
                logger.info("（PLSSOServerPlugin）callTrdSSOLogin()- 重定向到：" + loginUrl);
                response.sendRedirect(loginUrl);
                return;
            }


            if ("dd".equalsIgnoreCase(appType)) {
                Enumeration<String> enums = request.getParameterNames();
                StringBuilder sbBuilder = new StringBuilder();

                String name;
                while (enums.hasMoreElements()) {
                    name = (String) enums.nextElement();
                    if (!name.equals("redirect")) {
                        if (StringUtils.isEmpty(sbBuilder.toString())) {
                            sbBuilder.append("?").append(name).append("=");
                        } else {
                            sbBuilder.append("&").append(name).append("=");
                        }

                        sbBuilder.append(request.getParameter(name));
                    }
                }

                name = (new StringBuilder(server)).append("/qing/lappEntrance.do").append(sbBuilder).toString();
                String redirect = server + "/login-mobile.html?redirect=" + URLEncoder.encode(name, "UTF-8");
                logger.info("（PLSSOServerPlugin）callTrdSSOLogin()- 重定向移动端地址：" + redirect);
                response.sendRedirect(redirect);
                return;
            }

            if (threadLocal.get() != null && (Boolean) threadLocal.get()) {

                String accountId = request.getParameter("accountId");
                logger.info("（PLSSOServerPlugin）callTrdSSOLogin() - accountId" + accountId);
                request.removeAttribute("accountId");
                if (StringUtils.isBlank(accountId) || !YYACCOUNT_ID.equals(accountId)) {
                    logger.info("（PLSSOServerPlugin）callTrdSSOLogin()- accountId：是否为空");
                    accountId = "";
                }

                redirectUrl = this.getAuthUrl(response, HttpRequestUtil.getRequestURL(request), accountId);
                logger.info("（PLSSOServerPlugin）callTrdSSOLogin()- 更新后redirectUrl：" + redirectUrl);
            }

            logger.info("（PLSSOServerPlugin）callTrdSSOLogin()- 重定向地址：" + redirectUrl);
            this.authenticationRedirectStrategy.redirect(request, response, redirectUrl);
        } catch (IOException var12) {
            var12.printStackTrace();
            logger.error("（PLSSOServerPlugin）callTrdSSOLogin()- IOException e：" + var12);
        }


// 赋值正式环境代码
//        try {
//            String redirectUrl = CQLOGIN_URL;
//            //处理钉钉集成
//            String appType = request.getParameter("apptype");
//            String tenantId = RevProxyUtil.getTenantCode(request);
//            String server= UrlService.getDomainContextUrl(tenantId);
//
//            logger.info("（PLSSOServerPlugin）callTrdSSOLogin()- Request地址1：" + request.getRequestURL().toString());
//            logger.info("（PLSSOServerPlugin）callTrdSSOLogin()- RequestQueryString1：" + request.getQueryString());
//            if("dd".equalsIgnoreCase(appType)){
//                Enumeration<String> enums = request.getParameterNames();
//                StringBuilder sbBuilder = new StringBuilder();
//                while (enums.hasMoreElements()) {
//                    String name = enums.nextElement();
//                    if (!name.equals("redirect") ){
//                        if(StringUtils.isEmpty(sbBuilder.toString())){
//                            sbBuilder.append("?").append(name).append("=");
//                        }else{
//                            sbBuilder.append("&").append(name).append("=");
//                        }
//                        sbBuilder.append(request.getParameter(name));
//                    }
//                }
//               //2，生成返回的Url，包括查询参数
//                String OriginRedirect=new StringBuilder(server).append("/qing/lappEntrance.do").append(sbBuilder).toString();
//                //3，生成移动登录url，返回
//                String redirect = new StringBuilder(server).append("/login-mobile.html?redirect=").append( URLEncoder.encode(OriginRedirect,"UTF-8")).toString();
//                logger.info("（PLSSOServerPlugin）callTrdSSOLogin()- 重定向移动端地址：" + redirect);
//                response.sendRedirect(redirect);
//                return;
//            }
//            if (threadLocal.get() != null && (Boolean)threadLocal.get()) {
//                //判断数据中心
//                String accountId = request.getParameter("accountId");
//                request.removeAttribute("accountId");
//                //当请求链接包含数据中心，且为云商数据中心
//                if (StringUtils.isBlank(accountId)||!YYACCOUNT_ID.equals(accountId)) {
//                    accountId="";
//                }
//                logger.info("PLSSOServerPlugin）callTrdSSOLogin() accountId+" + accountId);
//
//
//                redirectUrl = this.getAuthUrl(response, HttpRequestUtil.getRequestURL(request),accountId);
//                //redirectUrl = loginUrl;
//                logger.info("PLSSOServerPlugin）callTrdSSOLogin() redirectUrl+" + redirectUrl);
//
//            }
//
//            logger.info("（PLSSOServerPlugin）callTrdSSOLogin()- 重定向地址：" + redirectUrl);
//            this.authenticationRedirectStrategy.redirect(request, response, redirectUrl);
//
//
//        } catch (IOException var5) {
//            var5.printStackTrace();
//            logger.info("（PLSSOServerPlugin）callTrdSSOLogin()- IOException e：" + var5);
//        }

//        try{
//            //清除缓存
//            /*if(cache.contains(tokenkey)){
//                cache.remove(tokenkey);
//            }*/
//
//            String redirectUrl = CQLOGIN_URL;//重定向地址
//            //未登入或验证失败，则跳转到认证地址
//            if(threadLocal.get() != null && threadLocal.get()){
//                redirectUrl = getAuthUrl(response, zjmi.cloud.bos.HttpRequestUtil.getRequestURL(request));//sso认证页面
//            }
//            logger.info("（PLSSOServerPlugin）callTrdSSOLogin()- 重定向地址："+redirectUrl);
//            this.authenticationRedirectStrategy.redirect(request, response, redirectUrl);
//        }catch (IOException e) {
//            e.printStackTrace();
//            logger.info("（PLSSOServerPlugin）callTrdSSOLogin()- IOException e："+e);
//        }

    }


    public UserAuthResult getTrdSSOAuth(HttpServletRequest request, HttpServletResponse response) {
        //
        //清除缓存
        //清除缓存
        logger.info("（PLSSOServerPlugin）callTrdSSOLogin()- Request地址：" + request.getRequestURL().toString());
        logger.info("（PLSSOServerPlugin）callTrdSSOLogin()- RequestQueryString：" + request.getQueryString());
        UserAuthResult result = new UserAuthResult();
        result.setSucess(false);
        result.setUserType(UserProperType.UserName);
        YSPLSsoParam param = new YSPLSsoParam(true);
        logger.info("生产环境 ==== 创建出来的 YSPLSsoParam param = " + param);
        String accountId = request.getParameter("accountId");

        Map<String, String[]> parameterMap = request.getParameterMap();
        String parameter = parameterMap.entrySet().stream()
                .map(entry -> entry.getKey() + "=" + String.join(",", entry.getValue()))
                .collect(Collectors.joining("&"));
        StringBuilder domainNameRequestAddressWithoutPort = new StringBuilder();
        domainNameRequestAddressWithoutPort.append(CALLBACK_URL).append("?").append(parameter);

        logger.info("（PLSSOServerPlugin）callTrdSSOLogin() + ParameterNames " + request.getParameterNames());
        logger.info("（PLSSOServerPlugin）callTrdSSOLogin() + parameter " + parameter);

        logger.info("（PLSSOServerPlugin）callTrdSSOLogin() + accountId " + accountId);
        request.removeAttribute("accountId");
        if (StringUtils.isNotBlank(accountId) && YYACCOUNT_ID.equals(accountId)) {
            logger.info("（PLSSOServerPlugin）callTrdSSOLogin() + accountId 2" + accountId);
            this.setParamData(param, true);
        } else {
            logger.info("（PLSSOServerPlugin）callTrdSSOLogin() + accountId 3" + accountId);
            accountId = ACCOUNT_ID;
            this.setParamData(param, false);
        }

        String targetUrl = "";
        String accessToken = request.getParameter("accessTokenKey");
        logger.info("（PLSSOServerPlugin）callTrdSSOLogin()- accessToken：" + accessToken);
        String pjtoken;
        if (StringUtils.isNotBlank(accessToken)) {
            logger.info("（PLSSOServerPlugin）()getTrdSSOAuth()- 获取token：" + accessToken);
            pjtoken = this.getLoginNameByToken(accessToken);
            if (StringUtils.isNotBlank(pjtoken)) {
                logger.info("（PLSSOServerPlugin）()getTrdSSOAuth()- loginName：" + pjtoken);
                result.setUser(pjtoken);
                result.setAccountId(accountId);
                result.setSucess(true);
                logger.info("（PLSSOServerPlugin）getTrdSSOAuth()- result设置成功：" + result);
                return result;
            }
        } else {
            logger.info("（PLSSOServerPlugin）getTrdSSOAuth()- 是否进入");
            pjtoken = HttpRequestUtil.getRequestURL(request);
            logger.info("（PLSSOServerPlugin）getTrdSSOAuth()- 请求地址：" + pjtoken);
            String code = request.getParameter("code");
            logger.info("（PLSSOServerPlugin）getTrdSSOAuth()- code：" + code);
            targetUrl = request.getParameter("target_uri");
            if (StringUtils.isNotBlank(code)) {
                accessToken = this.getAccessToken(code);
                logger.info("PLSSOServerPlugin）getTrdSSOAuth()- accessToken：" + accessToken);
                result = this.setUserAuthResult(result, accessToken, accountId);
            }
        }

        if (!result.isSucess()) {
            logger.info("PLSSOServerPlugin）getTrdSSOAuth()- isSucess：" + result.isSucess());
            threadLocal.set(true);
        }

        if (StringUtils.isNotBlank(targetUrl) && result.isSucess() && StringUtils.isNotBlank(accessToken)) {
            logger.info("PLSSOServerPlugin）getTrdSSOAuth()- isSucess 是否进去");
            try {
                targetUrl.replace("http", "https");
                targetUrl = URLDecoder.decode(targetUrl, "UTF-8");
                pjtoken = targetUrl.contains("?") ? "&accessTokenKey=" + accessToken : "?accessTokenKey=" + accessToken;

                targetUrl = targetUrl + pjtoken;
                logger.info("（PLSSOServerPlugin） + 跳转地址" + targetUrl);
                if (targetUrl.contains(":8082")) {
                    targetUrl = targetUrl.replace(":8082", "");
                    logger.info("（PLSSOServerPlugin） + 调整后跳转地址" + targetUrl);
                }
//                if (targetUrl.contains("ierp")) {
//                    targetUrl = targetUrl.replace("ierp", "");
//                    logger.info("(PIssoServerPlugin) + 调整后跳转地址" + targetUrl);
//                }
                if (targetUrl.contains("http://next-ierp/ierp?")) {
                    targetUrl = targetUrl.replace("http://next-ierp/ierp?", "https://opc.zmeeol.com/?");
                    logger.info("（PLSSOServerPlugin） + 调整后跳转地址" + targetUrl);
                }
                response.sendRedirect(targetUrl);
            } catch (IOException var10) {
                var10.printStackTrace();
                logger.error("getTrdSSOAuth IOException = " + var10);
            }
        }
        logger.info("PLSSOServerPlugin）getTrdSSOAuth() result" + result);


        String requestURL = request.getRequestURL().toString();
        //根据刘艳峰老师的需求：（1）getTrdSSOAuth事件中，判断url  httpServletRequest.getRequestURL().equals("http://gys.zmeeol.com") ，条件成立时 UserAuthResult .setSucess(false);
        if (REQUESTURL1.equals(requestURL) || REQUESTURL2.equals(requestURL)) {
            result.setSucess(false);
        }

        return result;


//        logger.info("（PLSSOServerPlugin）callTrdSSOLogin()- Request地址：" + request.getRequestURL().toString());
//        logger.info("（PLSSOServerPlugin）callTrdSSOLogin()- RequestQueryString：" + request.getQueryString());
//        UserAuthResult result = new UserAuthResult();
//        result.setSucess(false);
//        result.setUserType(UserProperType.UserName);
//        YSPLSsoParam param = new YSPLSsoParam(true);
//        //判断数据中心
//        String accountId = request.getParameter("accountId");
//        request.removeAttribute("accountId");
//        //当请求链接包含数据中心，且为医药数据中心
//        if (StringUtils.isNotBlank(accountId)&&YYACCOUNT_ID.equals(accountId)) {
//            this.setParamData(param,true);//设置云商的参数
//
//        }else{
//            accountId=ACCOUNT_ID;
//            this.setParamData(param,false);//设置共享数据中心参数
//        }
//
//        String targetUrl = "";
//        String accessToken = request.getParameter("accessTokenKey");
//        logger.info("（PLSSOServerPlugin）callTrdSSOLogin()- accessToken：" + accessToken);
//
//
//        //oa发送的用户登录名
//        String loginid=request.getParameter("loginid");
//        logger.info("（PLSSOServerPlugin）getloginid"+loginid);
//        //时间戳
//        String stamp=request.getParameter("timestamp");
//        logger.info("（PLSSOServerPlugin）stamp"+stamp);
//        //oa发送的验证token
//        String token=request.getParameter("loginTokenFromThird");
//        logger.info("（PLSSOServerPlugin）gettoken"+token);
//
//        Enumeration<String> parameterNames = request.getParameterNames();
//        logger.info("PLSSOServerPlugin + 参数名" + parameterNames.toString());
//
//
//        String pjtoken;
//        //链接包含登陆令牌直接校验通过6
//
//
//
//
//
//        if (StringUtils.isNotBlank(accessToken)) {
//            logger.info("（PLSSOServerPlugin）()getTrdSSOAuth()- 获取token：" + accessToken);
//            pjtoken = this.getLoginNameByToken(accessToken);
//            if (StringUtils.isNotBlank(pjtoken)) {
//                logger.info("（PLSSOServerPlugin）()getTrdSSOAuth()- loginName：" + pjtoken);
//                result.setUser(pjtoken);
//                result.setAccountId(accountId);
//                result.setSucess(true);
//                logger.info("（PLSSOServerPlugin）getTrdSSOAuth()- result设置成功：" + result);
//                return result;
//            }
//        }
//        else {
//            //链接不包含登陆令牌，获取人员登陆名，通过用户名校验通过
//            pjtoken = HttpRequestUtil.getRequestURL(request);
//
//            logger.info("（PLSSOServerPlugin）getTrdSSOAuth()- 请求地址：" + pjtoken);
//            String code = request.getParameter("code");
//            logger.info("（PLSSOServerPlugin）getTrdSSOAuth()- code：" + code);
//            targetUrl = request.getParameter("target_uri");
//            if (StringUtils.isNotBlank(code)) {
//                accessToken = this.getAccessToken(code);
//                result = this.setUserAuthResult(result, accessToken,accountId);
//            }
//        }
//
//        if (!result.isSucess()) {
//            threadLocal.set(true);
//        }
//
//        if (StringUtils.isNotBlank(targetUrl) && result.isSucess() && StringUtils.isNotBlank(accessToken)) {
//            try {
//                targetUrl.replace("http","https");
//                targetUrl = URLDecoder.decode(targetUrl, "UTF-8");
//                pjtoken = targetUrl.contains("?") ? "&accessTokenKey=" + accessToken : "?accessTokenKey=" + accessToken;
//                //云商会自动凭接上81端口，去掉该端口
//
//                //logger.info("（PLSSOServerPlugin） + 跳转地址" + targetUrl);
//                targetUrl = targetUrl + pjtoken;
//                logger.info("（PLSSOServerPlugin） + 跳转地址" + targetUrl);
////                if(targetUrl.contains("http://next-ierp/ierp?")){
////                    targetUrl = targetUrl.replace("http://next-ierp/ierp?","https://ebc.zjmiec.cn/ierp/?");
////                    logger.info("（PLSSOServerPlugin） + 调整后跳转地址" + targetUrl);
////                }
////                if(targetUrl.contains("next-ierp")){
////                    targetUrl = targetUrl.replace("next-ierp", "ebc-test.zjmiec.cn");
////                    //targetUrl = targetUrl.replace("next-ierp", "ebc.zjmiec.cn");
////
////
////
////                    logger.info("（PLSSOServerPlugin） + 调整后跳转地址" + targetUrl);
////                }
//
//                if(targetUrl.contains("next-ierp")){
//                    targetUrl = targetUrl.replace("next-ierp", "opctest.zmeeol.com");
//                    //targetUrl = targetUrl.replace("next-ierp", "ebc.zjmiec.cn");
//
//
//
//                    logger.info("（PLSSOServerPlugin） + 调整后跳转地址" + targetUrl);
//                }
//                response.sendRedirect(targetUrl);
//            } catch (IOException var9) {
//                var9.printStackTrace();
//            }
//        }
//
//        return result;
    }


    private void setParamData(YSPLSsoParam param, boolean isyy) {
        if (isyy) {
            //医药应用参数
            CLIENT_ID = param.getyyclientId();
            CLIENT_SECRET = param.getyySecret();
        } else {
            //共享应用参数
            CLIENT_ID = param.getClientId();
            CLIENT_SECRET = param.getSecret();
        }
        AUTHORIZE_URL = param.getAuthUrl();
        logger.info("setParamData - AUTHORIZE_URL = " + AUTHORIZE_URL);
        ACCESSTOKEN_URL = param.getAccessUrl();
        USER_URL = param.getUserUrl();
        CALLBACK_URL = param.getCallBackUrl();
        SSOLOGIN_URL = param.getPlLoginUrl();
    }

//    private void sendAuthUrl(HttpServletResponse response, String url) {
//        try {
//            String authUrl = this.getAuthUrl(response, url);
//            logger.info("（PLSSOServerPlugin）sendAuthUrl()- authUrl：" + authUrl);
//            response.sendRedirect(authUrl);
//        } catch (IOException var4) {
//            var4.printStackTrace();
//            logger.info("（PLSSOServerPlugin）sendAuthUrl()- IOException e：" + var4);
//        }
//
//    }

    private String getAuthUrl(HttpServletResponse response, String url, String accountId) {
        String authUrl = "";

        try {
            authUrl = AUTHORIZE_URL + "?client_id=" + CLIENT_ID + "&response_type=code&redirect_uri=" + URLEncoder.encode(CALLBACK_URL, "UTF-8") + "&oauth_timestamp=" + System.currentTimeMillis() + "&target_uri=" + URLEncoder.encode(url, "UTF-8");
            logger.info("PLSSOServerPlugin）getAuthUrl()- 回调地址" + authUrl);

//            if(accountId==null||"".equals(accountId)){
//
//                authUrl = AUTHORIZE_URL + "?client_id=" + CLIENT_ID + "&response_type=code&redirect_uri=" + URLEncoder.encode(CALLBACK_URL, "UTF-8") + "&oauth_timestamp=" + System.currentTimeMillis() + "&target_uri=" + URLEncoder.encode(url, "UTF-8");
//            }else{
//                authUrl = AUTHORIZE_URL + "?client_id=" + CLIENT_ID + "&response_type=code&redirect_uri=" + URLEncoder.encode(CALLBACK_URL+"?accountId="+accountId, "UTF-8") + "&oauth_timestamp=" + System.currentTimeMillis() + "&target_uri=" + URLEncoder.encode(url, "UTF-8");
//
//            }
        } catch (UnsupportedEncodingException var5) {
            var5.printStackTrace();
            logger.error("（PLSSOServerPlugin）getAuthUrl()- UnsupportedEncodingException e：" + var5);
        }

        return authUrl;
    }


    private UserAuthResult setUserAuthResult(UserAuthResult result, String accessToken, String accountId) {

        logger.info("（PLSSOServerPlugin）setUserAuthResult()- 获取到的token：" + accessToken);
        if (StringUtils.isNotBlank(accessToken)) {
            String loginName = this.getLoginNameByToken(accessToken);
            logger.info("（PLSSOServerPlugin）setUserAuthResult()- loginName：" + loginName);
            logger.info("（PLSSOServerPlugin）setUserAuthResult()- accountId：" + accountId);
            if (StringUtils.isNotEmpty(loginName)) {
                result.setUser(loginName);
                result.setAccountId(accountId);
                result.setSucess(true);
                logger.info("（PLSSOServerPlugin）setUserAuthResult()- result：" + result);
            }
        }

        return result;
    }

    private String getAccessToken(String code) {
        String accessToken = "";

        try {
            String accessTokenParam = HttpRequestUtil.getAccessTokenParam(CLIENT_ID, CLIENT_SECRET, CALLBACK_URL, code);
            logger.info("（PLSSOServerPlugin）getAccessToken()- accessTokenParam:" + accessTokenParam);
            String resultToken = HttpRequestUtil.getResult(ACCESSTOKEN_URL, accessTokenParam);
            logger.info("（PLSSOServerPlugin）getAccessToken()- resultToken:" + resultToken);
            JSONObject fromObject = JSONObject.fromObject(resultToken);
            int status = fromObject.getInt("status");
            if (status == 200) {
                accessToken = fromObject.getString("access_token");
            } else {
                logger.debug("（PLSSOServerPlugin）获取token失败，原因：" + fromObject.getString("msg"));
            }
        } catch (Exception var7) {
            var7.printStackTrace();
            logger.error("（PLSSOServerPlugin）getAccessToken()- exception e：" + var7);
        }

        return accessToken;
    }

    private String getLoginNameByToken(String token) {
        String loginName = "";

        try {
            if (StringUtils.isNotEmpty(token)) {
                String userParam = HttpRequestUtil.getUserParam(CLIENT_ID, CLIENT_SECRET, token);
                logger.info("（PLSSOServerPlugin）getLoginNameByToken()- userParam：" + userParam);
                String userJson = HttpRequestUtil.getResult(USER_URL, userParam);
                logger.info("（PLSSOServerPlugin）getLoginNameByToken()- userJson：" + userJson);
                JSONObject reqUser = JSONObject.fromObject(userJson);
                int status = reqUser.getInt("status");
                if (status == 200) {
                    loginName = reqUser.getString("id");
                } else {
                    logger.debug("（PLSSOServerPlugin）获取用户信息失败，原因：" + reqUser.getString("msg"));
                }
            }
        } catch (Exception var7) {
            var7.printStackTrace();
            logger.error("（PLSSOServerPlugin）getLoginNameByToken()-exception e：" + var7);
        }

        if (!StringUtils.equals("", loginName)) {
            logger.info("（PLSSOServerPlugin）getLoginNameByToken()-" + loginName);
            DynamicObject dynamicObject = BusinessDataServiceHelper.loadSingle("bos_user", "username", new QFilter[]{new QFilter("username", QCP.equals, loginName)});
            if (!ObjectUtils.isEmpty(dynamicObject)) {
                loginName = dynamicObject.getString("username");
                logger.info("（PLSSOServerPlugin）getLoginNameByToken()- oa账号转" + loginName);
            }
        }

        return loginName;
    }

    public void initialServiceData(HttpServletRequest request) {
        if (this.serverName == null) {
            this.serverName = RevProxyUtil.getURLContextPath(request);

        }

        if (this.service == null) {
            this.service = this.serverName + "index.html";
        }
        logger.info("（PLSSOServerPlugin）xw：" + this.serverName);
        logger.info("（PLSSOServerPlugin）xwservice：" + this.service);

    }

}
